package util工具包;

import java.sql.*;
import java.util.ResourceBundle;

//作用工具类
public class JDBCutil {
    private static  String driverName;
    private static String url;
    private static String username;
    private static String password;

    //静态代码块
    static {
        //读取jdbc.properties文件
        ResourceBundle jdbc = ResourceBundle.getBundle("JDBC");
        driverName = jdbc.getString("driverName");
        url = jdbc.getString("url");
        username = jdbc.getString("username");
        password = jdbc.getString("password");

    }
    //获取连接【静态方法 外界可以通过类名.方法名获取】
    public static Connection getconnection() {
        //1、加载驱动【告诉程序，我们要用什么版本的驱动，以及驱动在什么位置】
        //快捷键复制路径：三键：（ctrl+shift+alt+c）
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }


        //2、获取数据库连接对象【连接数据库】
        try {
            Connection conn = DriverManager.getConnection(url,username ,password );

                return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //如果报红就在这个位置return null;
    }

   //释放资源
    public static void close(Connection conn, PreparedStatement pst, ResultSet rs){

        if (rs!=null) {
            try {
                rs.close();
                System.out.println("rs释放成功");
            } catch (SQLException e) {
                System.out.println("rs释放失败");
                throw new RuntimeException(e);
            }
        }

        if (pst!=null) {
            try {
                pst.close();
                System.out.println("pst释放成功");
            } catch (SQLException e) {
                System.out.println("pst释放失败");
                throw new RuntimeException(e);
            }
        }

            if (conn!=null) {
                try {
                    conn.close();
                    System.out.println("conn释放成功");
                } catch (SQLException e) {
                    System.out.println("conn释放失败");
                    throw new RuntimeException(e);
                }
            }
    }



}
